#include "BasicTinyxml.h"

#include "./libsrc/tinyxml.h"
#include "BasicTranscode.h"

namespace utility
{
	BasicTinyxml::BasicTinyxml(void)
	{
		m_pDoc = new TiXmlDocument();
	}

	BasicTinyxml::~BasicTinyxml(void)
	{
		if( m_pDoc )
		{
			delete m_pDoc;
			m_pDoc = NULL;
		}
	}

	bool BasicTinyxml::LoadXmlFile( const TCHAR* szPath )
	{
		if( !szPath || !m_pDoc )
		{
			return false;
		}

#ifdef UNICODE
		std::string strPath;
		utility::BasicTranscode::Unicode_to_ANSI(szPath, strPath);
#else
		std::string strPath = szPath;
#endif
		bool bRet = m_pDoc->LoadFile( strPath.c_str() );

		return bRet && !m_pDoc->Error();
	}

	bool BasicTinyxml::LoadBuffer( const char* contents, size_t size )
	{
		if( !contents || !m_pDoc)
		{
			return false;
		}

		bool bRet = m_pDoc->Parse( contents, 0, TIXML_DEFAULT_ENCODING );

		return bRet && !m_pDoc->Error();
	}

	void BasicTinyxml::ReadString( const TCHAR* szKey, utility::string_t& strValue )
	{
		if( !szKey || !m_pDoc )
		{
			return ;
		}

		TiXmlElement * root_element = m_pDoc->RootElement();
		if( root_element == NULL )
			return;

#ifdef UNICODE
		std::string strName;
		std::string strValue_;
		utility::BasicTranscode::Unicode_to_ANSI(szKey, strName);
#else
		std::string strName = szKey;
		std::string strValue_;
#endif

		//root_element->QueryStringAttribute(strName.c_str(), &strValue_);
		this->ReadValue(strName.c_str(), strValue_ );

#ifdef UNICODE
		utility::BasicTranscode::ANSI_to_Unicode(strValue_.c_str(), strValue_.length(), strValue);
#else
		strValue = strValue_; 
#endif
	}

	void BasicTinyxml::ReadInteger( const TCHAR* szKey, int& nValue )
	{
		if( !szKey || !m_pDoc )
		{
			return ;
		}

		/*TiXmlElement * root_element = m_pDoc->RootElement();
		if( root_element == NULL )
			return;*/

#ifdef UNICODE
		std::string strName;
		utility::BasicTranscode::Unicode_to_ANSI(szKey, strName);
#else
		std::string strName = szKey;
#endif

		std::string strValue;
		this->ReadValue(strName.c_str(), strValue );
		nValue = /*_ttoi*/atoi(strValue.c_str());
		//root_element->QueryIntAttribute(strName.c_str(), &nValue);

	}

	void BasicTinyxml::ReadValue(const char* szKey, std::string& strValue)
	{
		if( !szKey )
		{
			return;
		}

		TiXmlElement * root_element = m_pDoc->RootElement();
		if( root_element == NULL )
			return;

		TiXmlElement * update_element = root_element->FirstChildElement( szKey );

		if( update_element != NULL && update_element->GetText() != NULL)
		{
			strValue = update_element->GetText();
		}

		/*TiXmlElement * update_element = root_element->FirstChildElement( "file" );
		while( update_element != NULL )
		{
			TiXmlElement * name_element = update_element->FirstChildElement( "name" );
			if( name_element != NULL && name_element->GetText() != NULL)
			{
				strValue = name_element->GetText();
			}
		}*/

	}
}
